import type { GreasyForkElements } from '../../../../../../../../../../types/constants/personalization/greasy_fork'
import { ThemeVarService } from '../../../../../../../../../../lib/abstract/style/theme_var/service'
import { PageHandler } from '../../../../../../../../../../lib/page_handler'
import {
  AppStyleCollections,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../../../../../types/constants'
import { getElementSelector } from '../../../../../../../../../../types/constants/personalization/common'
import { SYMBOLS } from '../../../../../../../../../../types/interfaces'

export enum DiscussionType {
  RATING = 'rating',
  FEEDBACK = 'feedback',
  QUESTION = 'question',
}

export enum RatingType {
  EXCELLENT = 'excellent',
  GOOD = 'good',
  POOR = 'poor',
}

// 测试链接：
// 1）https://greasyfork.org/zh-CN/scripts/457151/discussions/293890 （单个讨论）
// 1）https://greasyfork.org/zh-CN/scripts/490676/discussions/250574 （多个讨论：楼主、作者）
// 2）https://greasyfork.org/zh-CN/scripts/446342/discussions/272025（多个讨论：楼主、作者、左用户、右用户）
export class DiscussionPage {
  elements: GreasyForkElements = PAGE_ELEMENTS[SUPPORTED_PLATFORMS.GREASY_FORK]
  private readonly containerSelector = getElementSelector(this.elements, 'COMMON_CONTAINER')
  private readonly itemFullSelector = `${this.containerSelector} .comment`
  private static instance: DiscussionPage
  private pageHandler: PageHandler = PageHandler.getInstance()
  private readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()

  /**
   * 获取单例实例
   */
  public static getInstance(): DiscussionPage {
    if (!DiscussionPage.instance) {
      DiscussionPage.instance = new DiscussionPage()
    }
    return DiscussionPage.instance
  }

  init(): void {
    const $container = $(this.itemFullSelector)

    this.handleHeaderContent()

    $container.each((_index, element) => {
      const $element = $(element)
      const userLinkSelector = '.comment-meta .user-link'
      const selfLinkSelector = '.comment-meta .self-link'
      const $selfLink = $element.find(selfLinkSelector)

      // 隐藏锚点链接
      $selfLink.closest('.comment-meta-item').addClass(AppStyleCollections.Hide.ELEMENT)

      // 添加用户标签
      this.pageHandler.services.greasyFork.handleUserTag($element, userLinkSelector)
    })

    // 标识注销用户（测试链接：https://greasyfork.org/zh-CN/scripts/446342-telegram-media-downloader/discussions/299640）
    this.pageHandler.services.greasyFork.formatDeletedUser(`${this.itemFullSelector} .comment-meta > .comment-meta-item > i`)
  }

  handleHeaderContent(): void {
    // 处理讨论头部
    const $header = $('.discussion-header-script')
    const headerText = $header.find('h2').text().trim().toLowerCase()

    // 识别讨论类型
    let type = DiscussionType.QUESTION
    let rating: { level: string, label: string } | null = null
    if (headerText.startsWith('评价')) {
      type = DiscussionType.RATING
      rating = this.parseRating(headerText.replace('评价：', ''))
    }
    else if (headerText.startsWith('提问 / 留言')) {
      type = DiscussionType.FEEDBACK
    }

    // 设置数据属性
    $header.attr('data-type', type)
    if (rating) {
      $header.attr('data-rating', rating.level)
    }

    // 重构头部内容
    const $h2 = $header.find('h2')
    const newContent = this.formatHeaderContent(type, $h2.text().trim(), rating)
    $h2.empty().append(newContent)
  }

  private parseRating(text: string): { level: string, label: string } {
    if (text.startsWith('好评')) {
      return { level: RatingType.EXCELLENT, label: '好评' }
    }
    if (text.startsWith('一般')) {
      return { level: RatingType.GOOD, label: '一般评价' }
    }
    if (text.startsWith('差评')) {
      return { level: RatingType.POOR, label: '差评' }
    }
    return { level: RatingType.GOOD, label: '一般评价' }
  }

  private formatHeaderContent(type: DiscussionType, text: string, rating?: { level: string, label: string } | null): string {
    // 定义评价前缀正则表达式
    const ratingPrefixRegex = /^(评价：)?(好评|一般|差评)[\s-]*/

    switch (type) {
      case DiscussionType.RATING:
      // 移除评价前缀
      { const cleanedText = text.replace(ratingPrefixRegex, '').trim()
        return `
            <span class="header-label">${rating?.label}</span>
            <span class="header-text">${cleanedText}</span>
          ` }
      case DiscussionType.FEEDBACK:
        return `
          <span class="header-label">问题反馈</span>
        `
      default:
        return `
          <span class="header-label">问题咨询</span>
        `
    }
  }

  // 测试链接：https://greasyfork.org/zh-CN/scripts/14178/discussions/298495
  getMainStyles(): string {
    if (this.containerSelector.length === 0)
      return ''

    return `
${this.containerSelector} {
  /* 发布讨论 */
  #script-content {
    .post-discussion {
      .validation-errors {
        background: var(--${PROJECT_PREFIX}-theme-danger-bg) !important;
        border-left-color: var(--${PROJECT_PREFIX}-theme-danger-border) !important;
        
        p {
          color: var(--${PROJECT_PREFIX}-theme-danger-text) !important;
        }
      }
    }
    
    .discussion-header {
      .discussion-actions {
        display: flex !important;
        align-items: baseline !important;
      }
    }
  }

  /* 结果列表 */
  .comment {
    background: var(${this.themeVarService.default.background.left}) ;
    padding: ${this.themeVarService.default.style.padding};
    border-radius: ${this.themeVarService.default.style.borderRadius};
    
    &.${AppStyleCollections.Body.SCROLL_HIGHLIGHT} {
      background: var(${this.themeVarService.default.background.highlight}) !important;
      transition: background-color 2s ease-in-out;
    }
    
    .comment-meta {
      display: flex;
      align-items: center;
      
      .comment-meta-item {
        display: flex;
        align-items: center;
        white-space: nowrap !important;
        
        & > i {
          display: contents;
          .deleted-user-wrapper {
            display: contents;
          }
        }
      }
    }
    
    .user-content {
      background: var(${this.themeVarService.default.background.left});
      
      pre {
        &:hover {
          transform: none !important;
          box-shadow: none !important;
        }
      }
    }
  }
  
  .discussion-header-script {
    /* 评价标签样式 */
    &[data-rating="${RatingType.EXCELLENT}"] .header-label {
      background: linear-gradient(to right, rgba(76, 175, 80, 0.1), rgba(76, 175, 80, 0.15));
      
      &::before {
        content: "${SYMBOLS.STATUS.STAR_RATING}";
        margin-right: 4px;
      }
    }
    
    &[data-rating="${RatingType.GOOD}"] .header-label {
      background: linear-gradient(to right, rgba(255, 193, 7, 0.1), rgba(255, 193, 7, 0.15));
      
      &::before {
        content: "${SYMBOLS.STATUS.OK_RATING}";
        margin-right: 4px;
      }
    }
    
    &[data-rating="${RatingType.POOR}"] .header-label {
      background: linear-gradient(to right, rgba(244, 67, 54, 0.1), rgba(244, 67, 54, 0.15));
      
      &::before {
        content: "${SYMBOLS.STATUS.WARNING}";
        margin-right: 4px;
      }
    }

    /* 问题反馈标签样式 */
    &[data-type="${DiscussionType.FEEDBACK}"] .header-label {
      background: linear-gradient(to right, rgba(156, 39, 176, 0.1), rgba(156, 39, 176, 0.15));
      
      &::before {
        content: "${SYMBOLS.OTHERS.COMMENT}";
        margin-right: 4px;
      }
    }
    
    /* 问题咨询标签样式 */
    &[data-type="${DiscussionType.QUESTION}"] .header-label {
      background: linear-gradient(to right, rgba(33, 150, 243, 0.1), rgba(33, 150, 243, 0.15));
      
      &::before {
        content: "${SYMBOLS.OTHERS.HELP}";
        margin-right: 4px;
      }
    }
      
    h2 {
      display: flex;
      align-items: center;
      
      .header-label {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 500;
        white-space: nowrap;
        margin-right: 1rem;
        color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
      }
      
      /* 头部文本样式 */
      .header-text {
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
}
`
  }
}
